var express = require('express');
var router = express.Router();
var resultJson = require('../result-json');

var sha1 = require('sha1');
var config = require('../config');
var wxUtils = require('../utils/wxUtils');
var axios = require('axios')


router.get('/wxJssdk', function(req, res){

    var query = req.query;

    var token = config.wx.token;
    var timestamp = query.timestamp;
    var nonce = query.nonce;
     
    // 1）将token、timestamp、nonce三个参数进行字典序排序
    var list = [token, timestamp, nonce].sort()
     
    // 2）将三个参数字符串拼接成一个字符串进行sha1加密
    var str = list.join('');
    var result = sha1(str);
     
    // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
    if (result === query.signature) {

        res.send(query.echostr) // 返回微信传来的echostr，表示校验成功，此处不能返回其它

    } else {

        res.send(false)
    }

});


// 生成签名用于wx.config
router.get('/getWxConfig.json', (req, res) => {

	wxUtils.getToken_JsApi(data => {
	    
	    var noncestr = Math.random().toString(36).substr(2, 15) //随机字符串

	    var timestamp = parseInt(new Date().getTime() / 1000) + '' //获取当前时间戳, 单位秒

	    var url = req.query.url //获取前端页面的url, 不包括#及之后的内容

	    //按照微信的官方说法要将用于生成签名的noncestr timestamp url jsapi_ticket 按照ASCII码由小到大排序, 以键值对的形式
	    //拼接成字符串, "jsapi_ticket".charCodeAt()可查询
	    var str = 'jsapi_ticket=' + data.jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url ;

	    // 使用哈希加密成签名
	    var signature = sha1(str);   //npm install sha1

	    // 返回给前端
	    res.send(resultJson(0, {
	        appId: config.wx.appID,
	        signature: signature,
	        timestamp: timestamp,
	        noncestr: noncestr,
	        jsapi_ticket: data.jsapi_ticket
	    }))
	})

})


router.get('/checkWechatAuth.json', (req, res) => {

	var queryCode = req.query.code;

	let getRedirectUrl = () => {   //获取授权重定向地址

		let APPID = config.wx.appID;
		let rui = req.query.queryString;
		let code = 'code';
		let SCOPE = 'snsapi_userinfo';  // 需要用户授权
	  	let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${rui}&response_type=${code}&scope=${SCOPE}&state=STATE#wechat_redirect`
		
		return url;
	}

	let data = {};
	let wxToken = req.session.wxToken;

	if (wxToken){  //如果session中有wxToken ,刷新token并检验refresh_token是否过期

		if (wxToken.createTime){

			var now = new Date().getTime();

			if (parseInt(now) - parseInt(wxToken.createTime) > 6600*1000){  //微信授权asses_token有效期7200s，这里设置超过6600s就refresh_token


				wxUtils.refreshWxAccessToken(req).then(isSuccess => {

					if (isSuccess){  //未过期

						data =  {

							msg: '刷新access_token成功'
						};

						res.send(resultJson(0, data));
					} else {  

						if (queryCode){  //过期有code重新获取AccessToken

							wxUtils.getWxAccessToken(req).then(isSuccess => {

								data = {

									msg: '重新获取access_token授权成功'
								};

								res.send(resultJson(0, data));
							});
						} else { //过期且无code则重新走授权流程

							data = {
								url: getRedirectUrl()
							}

							res.send(resultJson(0, data));
						}
					}
				});
			} else {  //access_token未过期

				data =  {

					msg: 'access_token未过期'
				};

				res.send(resultJson(0, data));
			}
		}
	} else {

		if (queryCode){

			wxUtils.getWxAccessToken(req).then(isSuccess => {

				data = {

					msg: '获取access_token授权成功'
				};

				res.send(resultJson(0, data));
			});
		} else {

			data = {
				url: getRedirectUrl()
			}

			res.send(resultJson(0, data));
		}
		
	}
});

router.get('/getWechatRedirect.json', (req, res) => {

	let APPID = config.wx.appID;
	let rui = req.query.queryString;
	let code = 'code';
	let SCOPE = 'snsapi_userinfo';  // 需要用户授权
  	let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${rui}&response_type=${code}&scope=${SCOPE}&state=STATE#wechat_redirect`

	res.send(resultJson(0, {
		url: url
	}));
});


router.get('/getWxUser.json', (req, res) => {

	wxUtils.getWxUser(req).then(data => {
		
		res.send(resultJson(0, data));
	})
});

router.get('/clearWxSession.json', (req, res) => {

	req.session.wxToken = null;

	res.send(resultJson(0));
});



module.exports = router;